//
//  HZMSettingVC.m
//  糖糖大魔王
//
//  Created by 韩震明 on 15/11/9.
//  Copyright © 2015年 韩震明. All rights reserved.
//

#import "HZMSettingVC.h"
#import "HZMFeedbackVC.h"

@interface HZMSettingVC ()

@property(nonatomic, retain) NSString *cache;
@property(nonatomic, retain) UILabel *label;
@property(nonatomic, retain) NSString *environment;



@end

@implementation HZMSettingVC

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [self calculateTheCacheSize];
        [self checkTheNetworkEnvironment];
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIImage *nightImage = [self thumbnailWithImageWithoutScale:[UIImage imageNamed:@"4"] size:CGSizeMake(93, 93)];
    UIImage *cleanImage = [self thumbnailWithImageWithoutScale:[UIImage imageNamed:@"7"] size:CGSizeMake(93, 93)];
    
    UILabel *night = [[UILabel alloc] initWithFrame:CGRectMake(WIDTH / 41, 2 * HEIGHT / 74, 10 * WIDTH / 41, 5 * HEIGHT / 74)];
    night.text = @"夜间模式";
    [self.view addSubview:night];
    [night release];
    night.layer.borderWidth = 1;
    night.layer.cornerRadius = 5;
    
    UIButton *nightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    nightButton.frame = CGRectMake(30 * WIDTH / 41, 2 * HEIGHT / 74, WIDTH / 4, 5 * HEIGHT / 74);
    [self.view addSubview:nightButton];
    [nightButton setImage:nightImage forState:UIControlStateNormal];
    [nightButton addTarget:self action:@selector(nightButton:) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel *cleanCache = [[UILabel alloc] initWithFrame:CGRectMake(WIDTH / 41, 10 * HEIGHT / 74, 10 * WIDTH / 41, 5 * HEIGHT / 74)];
    cleanCache.text = @"清除缓存";
    [self.view addSubview:cleanCache];
    [cleanCache release];
    cleanCache.layer.borderWidth = 1;
    cleanCache.layer.cornerRadius = 5;
    
    UIButton *cleanButton = [UIButton buttonWithType:UIButtonTypeCustom];
    cleanButton.frame = CGRectMake(30 * WIDTH / 41, 10 * HEIGHT / 74, WIDTH / 4, 5 * HEIGHT / 74);
    [self.view addSubview:cleanButton];
    [cleanButton setImage:cleanImage forState:UIControlStateNormal];
    [cleanButton addTarget:self action:@selector(cleanButton:) forControlEvents:UIControlEventTouchUpInside];
    
    self.label = [[UILabel alloc] initWithFrame:CGRectMake(13 * WIDTH / 41, 10 * HEIGHT / 74, 17 * WIDTH / 41, 5 * HEIGHT / 74)];
    [self.view addSubview:_label];
    self.label.text = self.cache;
    [_label release];
    
    UIButton *callButton = [UIButton buttonWithType:UIButtonTypeSystem];
    callButton.frame = CGRectMake(20 * WIDTH / 41, 45 * HEIGHT / 74, 17 * WIDTH / 41, 5 * HEIGHT / 74);
    [self.view addSubview:callButton];
    [callButton setTitle:@"联系我们" forState:0];
    [callButton addTarget:self action:@selector(callUs) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *feedback = [UIButton buttonWithType:UIButtonTypeSystem];
    feedback.frame = CGRectMake(WIDTH / 41, 45 * HEIGHT / 74, 17 * WIDTH / 41, 5 * HEIGHT / 74);
    [self.view addSubview:feedback];
    [feedback setTitle:@"意见反馈" forState:0];
    [feedback addTarget:self action:@selector(goToFeedbackView) forControlEvents:UIControlEventTouchUpInside];
}

- (void)goToFeedbackView {
    HZMFeedbackVC *fVC = [[[HZMFeedbackVC alloc] init] autorelease];
    [fVC setModalTransitionStyle:2];
    [self presentViewController:fVC animated:YES completion:^{
        
    }];
}

- (void)callUs {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel://18642222320"]];
}

- (void)checkTheNetworkEnvironment {
    // 检测网络情况
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    self.environment = [NSString string];
    // 开始检测
    [manager startMonitoring];
    // 检测
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case -1:
                self.environment = @"未知";
                break;
            case 0:
                self.environment = @"无";
                break;
            case 1:
                self.environment = @"2G/3G/4G";
                break;
            case 2:
                self.environment = @"WiFi";
                break;
        }
        [self createLabel];
    }];
    // 停止检测
//    [manager stopMonitoring];
}

- (void)createLabel {
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(5 * WIDTH / 41, 20 * HEIGHT / 74, self.view.frame.size.width, 142 * HEIGHT / 736)];
    [self.view addSubview:label];
    [label release];
    label.font = [UIFont systemFontOfSize:14];
    
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    
    NSString *str = [NSString stringWithFormat:@"  当前网络:%@\n  版本相关\n  当前设备: %@\n  设备名: %@\n  系统版本: %@\n  APP名称: %@\n  APP版本: %@", self.environment, [[UIDevice currentDevice] model], [[UIDevice currentDevice] name], [[UIDevice currentDevice] systemVersion], [infoDictionary objectForKey:@"CFBundleName"], [infoDictionary objectForKey:@"CFBundleShortVersionString"]];
    label.text = str;
    label.numberOfLines = 12;
    [label sizeToFit];
}

- (void)calculateTheCacheSize {
    NSString *sandBoxPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject];
    NSString *CachesPath = [sandBoxPath stringByAppendingPathComponent:@"Caches"];
//    NSLog(@"%@", CachesPath);
    self.cache = [NSString stringWithFormat:@"所占空间:%.1fM", [self folderSizeAtPath:CachesPath]];
    
        _label.text = self.cache;
    
    
    NSLog(@"%@", self.cache);
}

- (void)cleanButton:(UIButton *)cleanButton
{
    NSString *sandBoxPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject];
    NSString *CachesPath = [sandBoxPath stringByAppendingPathComponent:@"Caches"];
    
    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:CachesPath];
    for (NSString *p in files) {
        NSError *error;
        NSString *Path = [CachesPath stringByAppendingPathComponent:p];
        if ([[NSFileManager defaultManager] fileExistsAtPath:Path]) {
            [[NSFileManager defaultManager] removeItemAtPath:Path error:&error];
        }
    }
    _label.text = self.cache;
    [self performSelectorOnMainThread:@selector(clearCacheSuccess) withObject:nil waitUntilDone:YES];
}



// 查看当前缓存所占空间
- (CGFloat) folderSizeAtPath:(NSString*) folderPath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:folderPath]) return 0;
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    NSString* fileName;
    CGFloat folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        NSString *fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    NSLog(@"%f", folderSize / (1024.0 * 1024.0));
    return folderSize / (1024.0 * 1024.0);
}

- (CGFloat) fileSizeAtPath:(NSString*) filePath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}

-(void)clearCacheSuccess {
    [self calculateTheCacheSize];
//    [self.tableView reloadData];
    UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:@"提示" message:@"清理缓存成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil] autorelease];
    [alert show];
}



- (void)nightButton:(UIButton *)nightButton
{
    // 假夜间
    [(AppDelegate *)[UIApplication sharedApplication].delegate change];
}

- (UIImage *)thumbnailWithImageWithoutScale:(UIImage *)image size:(CGSize)asize
{
    UIImage *newimage;
    if (nil == image) {
        newimage = nil;
    }
    else{
        CGSize oldsize = image.size;
        CGRect rect;
        if (asize.width/asize.height > oldsize.width/oldsize.height) {
            rect.size.width = asize.height*oldsize.width/oldsize.height;
            rect.size.height = asize.height;
            rect.origin.x = (asize.width - rect.size.width)/2;
            rect.origin.y = 0;
        }
        else{
            rect.size.width = asize.width;
            rect.size.height = asize.width*oldsize.height/oldsize.width;
            rect.origin.x = 0;
            rect.origin.y = (asize.height - rect.size.height)/2;
        }
        UIGraphicsBeginImageContext(asize);
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSetFillColorWithColor(context, [[UIColor clearColor] CGColor]);
        UIRectFill(CGRectMake(0, 0, asize.width, asize.height));//clear background
        [image drawInRect:rect];
        newimage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }
    return newimage;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
